package com.observer.service.impl;

import com.observer.entity.Weather;
import com.observer.service.Observer;
import com.observer.service.Subject;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.cleaver.spring.application.ApplicationContextUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 天气情况主题发布者
 *
 * @author LiKun
 * @date 2021/8/5 22:58
 */
@Data
@Component
@NoArgsConstructor
public class WeatherSubject implements Subject {
    private Weather weather;
    private List<Observer> observers;

    @Resource
    private ApplicationContext applicationContext;

    public WeatherSubject(Weather weather) {
        this.weather = weather;
    }

    @PostConstruct
    public void initialize() {
        observers = ApplicationContextUtil.getRealizeBeanList(Observer.class);
    }

    @Override
    public void notifyObserver() {
        observers.forEach(data -> data.update(weather));
    }

    @Override
    public void removeObserver(Observer observer) {
        this.observers.remove(observer);
    }

    @Override
    public void registerObserver(Observer observer) {
        this.observers.add(observer);
    }
}
